<script setup lang="ts">
import { useAsideStore } from '@store/aside'
import { useRouter, useRoute } from 'vue-router'
import { ref, watchEffect } from 'vue'
import { deepSeekArrayValue } from '@/utils'
import setting_img from '@/assets/images/setting.png'

interface AsideListInterface {
  id: number
  index: string
  disabled: boolean
  name: string
  path: string
  children?: AsideListInterface[]
}

defineOptions({
  name: 'Aside',
})

const asideStore = useAsideStore()

const asideList = ref(asideStore.asideList)
const router = useRouter()
const route = useRoute()

const menuChange = (index: string) => {
  const currentItem = deepSeekArrayValue<AsideListInterface>(
    asideList.value,
    index,
  )
  console.log(currentItem)
  if (currentItem?.path) {
    // 跳转
    router.push(`${currentItem.path}`)
  }
}

// 刷新页面侧边栏的高亮保留, 默认为主页的index
const defaultActive = ref('')
watchEffect(() => {
  const currentItem = deepSeekArrayValue<AsideListInterface>(
    asideList.value,
    route.meta.id as string,
    'id',
  )
  defaultActive.value = currentItem.index
})
</script>

<template>
  <div class="aside-container">
    <ElMenu
      class="aside-container-menu"
      mode="vertical"
      :default-active="defaultActive"
      @select="menuChange"
    >
      <template v-for="item in asideList" :key="item.id">
        <!-- 子级 -->
        <ElSubMenu
          v-if="item.children?.length"
          :index="item.index"
          :disabled="item.disabled"
        >
          <template #title>
            <div class="aside-submenu-title">
              {{ item.name }}
            </div>
          </template>
          <ElMenuItem
            v-for="child in item.children"
            :key="child.id"
            :index="child.index"
            :disabled="child.disabled"
          >
            <div class="aside-menu-item">{{ child.name }}</div>
          </ElMenuItem>
        </ElSubMenu>
        <!-- 没有子级 -->
        <ElMenuItem v-else :index="item.index" :disabled="item.disabled">
          <div class="aside-menu-item">{{ item.name }}</div>
        </ElMenuItem>
      </template>
    </ElMenu>

    <div class="aside-setting">
      <div class="icon">
        <img v-bind:src="setting_img" alt="setting" />
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
@use './aside.scss';
</style>
<style lang="scss">
.el-sub-menu__title {
  height: 43px;
  color: var(--textGrayColor);
  font-size: 14px;
  border-radius: 4px;

  .aside-submenu-title {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 100%;
    text-align: center;
  }

  &:hover {
    background-color: var(--primaryBack);
    color: var(--textColor);
  }
}
</style>
